package cn.rwklyd.BookKeeping.controller;

import cn.rwklyd.BookKeeping.constant.MessageConstant;
import cn.rwklyd.BookKeeping.pojo.Result;
import cn.rwklyd.BookKeeping.pojo.dto.EmailRequest;
import cn.rwklyd.BookKeeping.pojo.dto.VerifyCodeRequest;
import cn.rwklyd.BookKeeping.util.AliOssUtil;
import cn.rwklyd.BookKeeping.util.EmailUtils;
import cn.rwklyd.BookKeeping.util.ImageModerationUtil;
import cn.rwklyd.BookKeeping.util.RedisUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 通用接口
 */
@RestController
@RequestMapping("/admin/common")
@Tag(name = "通用接口", description = "通用接口")
@Slf4j
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private EmailUtils emailUtils;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private ImageModerationUtil imageModerationUtil;

    private final ObjectMapper objectMapper = new ObjectMapper();  // JSON解析器
    
    // Redis验证码前缀
    private static final String VERIFICATION_CODE_PREFIX = "verification:code:";
    // 验证码有效期（分钟）
    private static final long VERIFICATION_CODE_EXPIRE = 5;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    @Operation(summary = "文件上传接口", description = "文件上传接口")
    @Parameter(name = "file", description = "文件", required = true)
    @Parameter (name = "folderPath", description = "上传的文件夹路径", required = true)
    public Result<String> upload(@RequestParam("file") MultipartFile file,
                                 @RequestParam(value = "folderPath", required = false) String folderPath) {
        log.info("文件上传：{}", file);
        if (file == null) {
            return Result.error(MessageConstant.UPLOAD_NOT_EXISTS);
        }

        try {
            // 原始文件名
            String originalFilename = file.getOriginalFilename();
            // 截取原始文件名的后缀
            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
            // 构造新文件名称
            String objectName = folderPath + "/" + UUID.randomUUID().toString() + extension;
            // 文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);

            // 自动审核图片
//            String dataId = UUID.randomUUID().toString();
//            String responseJson = imageModerationUtil.moderateImage(filePath, dataId);
//            // 解析JSON响应
//            JsonNode responseNode = objectMapper.readTree(responseJson);
//            String riskLevel = responseNode.path("data").path("riskLevel").asText();
//            if ("high".equals(riskLevel)) {
//                String description = responseNode.path("data").path("results").get(0).path("result").get(0).path("description").asText();
//                aliOssUtil.deleteFile(objectName);    // 删除违规图片
//                return Result.error("图片违规(" + description + ")");
//            }
            return Result.success(filePath);

        } catch (IOException e) {
            log.error("文件上传失败：{}", e);
            return Result.error(MessageConstant.UPLOAD_FAILED);
        } catch (Exception e) {
            log.error("图片审核失败：{}", e);
            return Result.error(MessageConstant.SCAN_FAILED);
        }
    }

    /**
     * 发送验证码邮件
     */
    @PostMapping("/sendVerificationCode")
    @Operation(summary = "发送验证码邮件", description = "发送包含验证码的邮件")
    public Result<String> sendVerificationCode(@RequestBody EmailRequest request) {
        log.info("发送验证码邮件: {}", request);
        
        // 验证参数
        if (request.getEmail() == null || request.getEmail().isEmpty()) {
            return Result.error("邮箱地址不能为空");
        }
        
        // 生成验证码
        String code = emailUtils.generateVerificationCode();
        
        // 使用默认内容或自定义内容
        String content = request.getContent();
        if (content == null || content.isEmpty()) {
            content = "<p>您好，您正在注册个人记账本账号，验证码为：</p>";
        }
        
        // 发送邮件
        boolean success = emailUtils.sendCustomEmail(
            request.getEmail(),
            "个人记账本 - 验证码",
            content,
            code
        );
        
        if (success) {
            // 将验证码存入Redis，设置5分钟过期
            String redisKey = VERIFICATION_CODE_PREFIX + request.getEmail();
            redisUtils.set(redisKey, code, VERIFICATION_CODE_EXPIRE, TimeUnit.MINUTES);
            log.info("验证码已保存到Redis: {}, 有效期{}分钟", redisKey, VERIFICATION_CODE_EXPIRE);
            
            // 返回成功信息，但不返回验证码（安全考虑）
            return Result.success("验证码发送成功");
        } else {
            return Result.error("邮件发送失败，请稍后重试");
        }
    }
    
    /**
     * 验证验证码
     */
    @PostMapping("/verifyCode")
    @Operation(summary = "验证验证码", description = "验证邮箱验证码是否正确")
    public Result<Boolean> verifyCode(@RequestBody VerifyCodeRequest request) {
        log.info("验证验证码: {}", request);
        
        // 验证参数
        if (request.getEmail() == null || request.getEmail().isEmpty()) {
            return Result.error("邮箱地址不能为空");
        }
        if (request.getCode() == null || request.getCode().isEmpty()) {
            return Result.error("验证码不能为空");
        }
        
        // 从Redis获取验证码
        String redisKey = VERIFICATION_CODE_PREFIX + request.getEmail();
        String savedCode = redisUtils.get(redisKey);
        
        if (savedCode == null) {
            return Result.error("验证码已过期或不存在");
        }
        
        // 验证码比对
        if (savedCode.equals(request.getCode())) {
            // 验证成功后删除验证码，防止重复使用
            redisUtils.delete(redisKey);
            return Result.success(true);
        } else {
            return Result.error("验证码错误");
        }
    }
    
    /**
     * 发送自定义邮件
     */
    @PostMapping("/sendCustomEmail")
    @Operation(summary = "发送自定义邮件", description = "发送自定义内容的邮件")
    public Result<String> sendCustomEmail(@RequestBody EmailRequest request) {
        log.info("发送自定义邮件: {}", request);
        
        // 验证参数
        if (request.getEmail() == null || request.getEmail().isEmpty()) {
            return Result.error("邮箱地址不能为空");
        }
        if (request.getContent() == null || request.getContent().isEmpty()) {
            return Result.error("邮件内容不能为空");
        }
        
        String subject = request.getSubject() != null && !request.getSubject().isEmpty() 
                        ? request.getSubject() : "个人记账本 - 通知";
        
        // 发送邮件
        boolean success = emailUtils.sendCustomEmail(
            request.getEmail(),
            subject,
            request.getContent(),
            request.getCode()
        );
        
        if (success) {
            return Result.success("邮件发送成功");
        } else {
            return Result.error("邮件发送失败，请稍后重试");
        }
    }


}
